#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime
import math
import json
import logging

from sqlalchemy import or_

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

from app import db
from models.article import Article
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
from models import BaseModel


class ArticleController(Article,BaseModel):

    @classmethod
    def add(cls, **kwargs):
        try:
            # 创建文章记录
            article = Article(
                title=kwargs.get('title'),
                psy_id=kwargs.get('psy_id'),
                content=kwargs.get('content'),
                publish_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            )
            db.session.add(article)
            db.session.commit()

            logger.info(f'文章添加成功，article_id: {article.article_id}')
            return {'code': RET.OK, 'message': '文章添加成功', 'data': None}

        except Exception as e:
            # 回滚事务并返回错误信息
            db.session.rollback()
            logger.error(f'添加文章时发生错误: {str(e)}')
            return {'code': RET.DBERR, 'message': '数据库错误', 'data': str(e)}

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = [cls.is_delete == 0]
            if kwargs.get('article_id'):
                filter_list.append(cls.article_id == kwargs['article_id'])
            else:
                if kwargs.get('title'):
                    filter_list.append(cls.title == kwargs.get('title'))
                if kwargs.get('psy_id') is not None:
                    filter_list.append(cls.psy_id == kwargs.get('psy_id'))
                if kwargs.get('publish_time'):
                    filter_list.append(cls.publish_time == kwargs.get('publish_time'))
                if kwargs.get('content'):
                    filter_list.append(cls.content == kwargs.get('content'))
                if kwargs.get('create_time'):
                    filter_list.append(cls.create_time == kwargs.get('create_time'))
                if kwargs.get('update_time'):
                    filter_list.append(cls.update_time == kwargs.get('update_time'))
                

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            article_info = db.session.query(cls).filter(*filter_list)
            
            count = article_info.count()
            pages = math.ceil(count / size)
            article_info = article_info.limit(size).offset((page - 1) * size).all()
   
            #results = commons.query_to_dict(article_info)
            results = cls.to_dict(article_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
            
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        @classmethod
        def delete(cls, **kwargs):
            """
            删除文章
            :param kwargs: 包含文章ID的字典
            :return: 返回操作结果（code, message, data）
            """
            try:
                article_id = kwargs.get('article_id')
                if not article_id:
                    return {'code': RET.PARAMERR, 'message': '文章ID不能为空', 'data': None}

                # 查询数据库中的文章记录
                article = Article.query.filter_by(article_id=article_id).first()
                if not article:
                    return {'code': RET.NODATA, 'message': '文章不存在', 'data': None}

                # 删除文章记录
                db.session.delete(article)
                db.session.commit()

                return {'code': RET.OK, 'message': '文章删除成功', 'data': None}

            except Exception as e:
                # 回滚事务并返回错误信息
                db.session.rollback()
                return {'code': RET.DBERR, 'message': '数据库错误', 'data': str(e)}
    
    # update
    @classmethod
    def update(cls, **kwargs):
        try:
            
            
            filter_list = [cls.is_delete == 0]
            filter_list.append(cls.article_id == kwargs.get('article_id'))
            
            res = db.session.query(cls).filter(*filter_list).with_for_update()
            if res.first():
                results = {
                    'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    'article_id': res.first().article_id,
                
                }
                
                res.update(kwargs)
                db.session.commit()
            else:
                results = {
                    'error': 'data dose not exist'
                }

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # batch add
    @classmethod
    def add_list(cls, **kwargs):
        param_list = kwargs.get('ArticleList')
        model_list = []
        for param_dict in param_list:
            from utils.generate_id import GenerateID
            article_id = GenerateID.create_random_id()

            model = Article(
                article_id=article_id,
                title=param_dict.get('title'),
                psy_id=param_dict.get('psy_id'),
                publish_time=param_dict.get('publish_time'),
                content=param_dict.get('content'),
                create_time=param_dict.get('create_time'),
                update_time=param_dict.get('update_time'),

            )
            model_list.append(model)

        try:
            db.session.add_all(model_list)
            db.session.commit()
            results = {
                'added_records': [],
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            for model in model_list:
                added_record = {}
                added_record['article_id'] = model.article_id

                results['added_records'].append(added_record)

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

